package com.qf.ssm.controller;

import com.qf.ssm.entity.User;
import com.qf.ssm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author manchi520
 * @date 2022/7/9
 * @apiNote
 */
@Slf4j
public class AutoLoginInterceptor implements HandlerInterceptor {
    UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User userToken = (User) request.getSession().getAttribute("user");
        if (userToken != null) {
            response.sendRedirect("main.html");
            log.debug("当前用户已登录，重定向到main.html");
            return true;
        }
        //获取cookie中的userToken数据 判断是否可以自动登录
        Cookie[] cookies = request.getCookies();

        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("userToken")) {
                    String value = cookie.getValue();  //格式为username-password
                    String[] split = value.split("-");
                    String username = split[0];
                    String password = split[1];
                    log.debug("拦截器校验用户名和密码，username={},password={}", username, password);
                    User user = userService.login(username, password);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                        log.debug("恢复登录状态成功，user={}", user);
                        response.sendRedirect("main.html");
                        return false;
                    }
                }
            }
        }
        log.debug("无法正常免登录，正在跳转到登录页面");
        //表示放行
        return true;
    }
}
